package com.teachoa.web;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.jfinal.plugin.activerecord.Page;
import com.teachoa.bean.Course;
import com.teachoa.bean.Dict;
import com.teachoa.bean.User;
import com.teachoa.constant.Global;
import com.teachoa.enumtype.UserTypeEnum;
import com.teachoa.util.DictUtil;
import com.teachoa.util.IDUtil;
import com.teachoa.util.Maps;

public class CourseController extends BaseController {
	
	public void index() {
		int pageNo = getParaToInt("pageNo", 1);
		setAttr("coursePage", Course.dao.findByPage(pageNo));
		renderJsp("course.jsp");
	}
	
	public void dialog() {
		String id = getPara();
		if(StringUtils.isNotEmpty(id)) {
			Course course = Course.dao.findById(id);
			String userId = course.getStr("user_id");
			User user = User.dao.findById(userId);
			course.put("user_name", user.getStr("username"));
			setAttr("course", course);
		}
		setAttr("types", Dict.dao.getSubDictsByPath(Global.courseTypePath));
		Page<User> userPage = User.dao.findUserByPage(new HashMap<String, String>());
		Map<Integer, String> sexMap = DictUtil.getDictMapByPath(Global.sexPath);
		for(User user:userPage.getList()) {
			user.put("sex_display", sexMap.get(user.getInt("sex")));
			user.put("type_display", UserTypeEnum.getEnumByCode(user.getInt("type")).getDesc());
		}
		setAttr("userPage", userPage);
		renderJsp("course_add.jsp");
	}
	
	public void save() {
		try {
			Course course = getModel(Course.class);
			if(StringUtils.isEmpty(course.getStr("id"))) {
				course.set("id", IDUtil.getId());
				course.set("create_time", new Date());
				course.save();
			} else {
				course.update();
			}
			renderJson(success("保存成功！！"));
		} catch (Exception e) {
			e.printStackTrace();
			renderJson(fail("保存失败！！"));
		}
	}
	
	public void del() {
		try {
			Course.dao.deleteById(getPara());
			renderJson(success("删除成功！！"));
		} catch (Exception e) {
			renderJson(fail("删除失败！！"));
		}
	}
	
	public void view() {
		Course course = Course.dao.findById(getPara());
		String userId = course.getStr("user_id");
		User user = User.dao.findById(userId);
		course.put("user_name", user.getStr("username"));
		setAttr("types", Dict.dao.getSubDictsByPath(Global.courseTypePath));
		setAttr("course", course);
		renderJsp("course_view.jsp");
	}
	
	public void userPage() {
		Page<User> userPage = User.dao.findUserByPage(super.getParamMap());
		Map<Integer, String> sexMap = DictUtil.getDictMapByPath(Global.sexPath);
		for(User user:userPage.getList()) {
			user.put("sex_display", sexMap.get(user.getInt("sex")));
			user.put("type_display", UserTypeEnum.getEnumByCode(user.getInt("type")).getDesc());
		}
		setAttr("userPage", userPage);
		renderJsp("user_table.jsp");
	}

}
